package com.cj.wisdom_display

import android.annotation.SuppressLint
import android.os.Handler
import android.os.Looper
import android.os.Message
import android_serialport_api.ByteUtils
import android_serialport_api.MathUtil
import android_serialport_api.SerialHelper
import com.cj.wisdom_display.client.NettyTcpClient
import com.cj.wisdom_display.client.constant.ConnectState.Companion.STATUS_CONNECT_CLOSED
import com.cj.wisdom_display.client.constant.ConnectState.Companion.STATUS_CONNECT_ERROR
import com.cj.wisdom_display.client.constant.ConnectState.Companion.STATUS_CONNECT_SUCCESS
import com.cj.wisdom_display.utils.*
import com.cj.wtrails.observer.MyObserver
import com.lztek.toolkit.Lztek
import com.safframework.netty4android.client.listener.NettyClientListener
import com.youth.banner.indicator.CircleIndicator
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.item_img.*
import kotlinx.android.synthetic.main.layout_bottom.*
import kotlinx.android.synthetic.main.layout_top.*
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit
import kotlin.system.exitProcess


class MainActivity : BaseActivity(), MyObserver.MyObserverListener, NettyClientListener<String> {

    lateinit var controller: MainController
    lateinit var serialHelper: SerialHelper
    var disposable: Disposable? = null
    var disposable1: Disposable? = null
    var disposable2: Disposable? = null
    var musicPlayer: MusicPlayer? = null
    private lateinit var mNettyTcpClient: NettyTcpClient
    private var ip: String = BuildConfig.HOST_IP
    private var port: Int = 8810

    override fun layoutId(): Int {
        return R.layout.activity_main
    }

    override fun findView() {
        //添加生命周期观察者
        banner.addBannerLifecycleObserver(this)
        controller = MainController(handler, this)
        serialHelper = object : SerialHelper() {
            override fun onDataReceived(buff: ByteArray?) {
                LogUtil.e("返回数据1：${MathUtil.bytesToHex(buff)}")
                LogUtil.e("返回数据2：${ByteUtils.bytesToHexString(buff)}")
                val string=ByteUtils.bytesToHexString(buff)
                if (string.length==30){
                    runOnUiThread {
                        val shidu = string.substring(6, 10)
                        val wendu = string.substring(10, 14)
                        val zaosheng = string.substring(14, 18)
                        val pm = string.substring(18, 22)

                        val s1 = Integer.parseInt(shidu, 16) / 10
                        val s2 = Integer.parseInt(wendu, 16) / 10
                        val s3 = Integer.parseInt(zaosheng, 16) / 10
                        val s4 = Integer.parseInt(pm, 16)

                        LogUtil.e("湿度：$s1")
                        LogUtil.e("温度：$s2")
                        LogUtil.e("噪声：$s3")
                        LogUtil.e("pm2.5：$s4")
                        image_text_1.setTxt2(s2.toString())
                        image_text_2.setTxt2(s1.toString())
                        image_text_3.setTxt2(s4.toString())
                        image_text_4.setTxt2(s3.toString())
                    }
                }
            }

            override fun onSendDataReceived(buff: ByteArray?) {
                LogUtil.e("发送数据：${MathUtil.bytesToHex(buff)}")
            }
        }
        serialHelper.open()
        if (serialHelper.isOpen) {
            LogUtil.e("串口打开成功")
        } else {
            LogUtil.e("串口打开失败")
            serialHelper.open()
        }

        interval(0, 30, TimeUnit.MINUTES, object : LongObserver() {
            override fun onSubscribe(d: Disposable) {
                disposable = d
            }

            override fun onNext(t: Long) {
                //发送数据
                serialHelper.send(MathUtil.hexString2Bytes("040301F40005C592"))
            }
        })

        /*val string = "04030A021D00F30223002600367ADE"
        val shidu = string.substring(6, 10)
        val wendu = string.substring(10, 14)
        val zaosheng = string.substring(14, 18)
        val pm = string.substring(18, 22)

        val s1 = Integer.parseInt(shidu, 16) / 10
        val s2 = Integer.parseInt(wendu, 16) / 10
        val s3 = Integer.parseInt(zaosheng, 16) / 10
        val s4 = Integer.parseInt(pm, 16)

        LogUtil.e("湿度：$s1")
        LogUtil.e("温度：$s2")
        LogUtil.e("噪声：$s3")
        LogUtil.e("pm2.5：$s4")
        image_text_1.setTxt2(s2.toString())
        image_text_2.setTxt2(s1.toString())
        image_text_3.setTxt2(s4.toString())
        image_text_4.setTxt2(s3.toString())

        controller.environment(s2, s4, s3, s1)*/

    }

    override fun initView() {
        initClient()
        controller.getParkInfo()
        interval(0, 30, TimeUnit.MINUTES, object : LongObserver() {
            override fun onNext(t: Long) {
                controller.getParkInfo()
            }

            override fun onSubscribe(d: Disposable) {
                disposable2 = d
            }
        })
        controller.getNotice()
        initLztek()
    }

    override fun setListener() {
    }

    override fun onStart() {
        super.onStart()
        //开始轮播
        banner.start()
    }

    override fun onResume() {
        super.onResume()
        connect()
    }

    override fun onStop() {
        super.onStop()
        //停止轮播
        banner.stop()
        musicPlayer?.stop()
    }

    override fun onPause() {
        super.onPause()
        exitProcess(0)
    }

    override fun onDestroy() {
        musicPlayer?.onDestroyed()
        disposable?.dispose()
        disposable1?.dispose()
        disposable2?.dispose()
        banner.destroy()
        handler.removeCallbacksAndMessages(null)
        tv_notice.stopRoll()
        mNettyTcpClient.disconnect()
        super.onDestroy()
    }

    fun initPlayer(url: String) {
        musicPlayer = MusicPlayer(url)
        musicPlayer?.setOnSeekListener(object : MusicPlayer.OnSeekListener {
            override fun OnSeek(per_100: Int) {

            }

            override fun onComplete() {
                musicPlayer?.onDestroyed()
                //重复播放
                initPlayer(url)
                //musicPlayer?.start()
            }

            override fun loadComplete() {
                //可以播放音乐了
                musicPlayer?.start()
            }
        })
    }

    private val handler = @SuppressLint("HandlerLeak")
    object : Handler(Looper.getMainLooper()) {
        @SuppressLint("SetTextI18n", "SimpleDateFormat")
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                101 -> {
                    controller.weather?.apply {
                        iv_weather_img.showImg(this.img)
                        tv_weather_text.text = this.temperature
                        tv_weather_address1.text = this.text
                        tv_weather_date.text = SimpleDateFormat("yyyy年MM月dd日").format(Date())
                        tv_weather_date1.text = SimpleDateFormat("EEEE").format(Date())
                    }
                }
                102 -> {
                    controller.parkEntity?.apply {
                        tv_info_text1.text = "工作日游园时间：" + this.workOpenTime
                        tv_info_text2.text = "周末游园时间：" + this.weekendOpenTime
                        tv_info_text3.text = "公园地址：" + this.address
                        tv_info_text4.text = "客服电话：" + this.phone
                        tv_park_name.text = this.title
                        tv_weather_address.text = cityName
                        if (this.cityName.isNotEmpty()) {
                            controller.getWeather(cityName)
                        }
                        if (!this.pictures.isNullOrEmpty()) {
                            banner.addBannerLifecycleObserver(this@MainActivity)//添加生命周期观察者
                                .setAdapter(ImageAdapter(pictures))
                                //.indicator = CircleIndicator(this@MainActivity)
                                .setBannerRound2(10f)
                                .setBannerGalleryEffect(0, 0, 10)
                                .setLoopTime(3000).scrollTime = 1500

                            //只有一张不滑动
                            if (pictures.size == 1) {
                                banner.stop()
                            }
                        }
                    }
                }
                103 -> {
                    controller.notice?.apply {
                        tv_notice.setContent(this.content)
                        when (typeName) {
                            "紧急公告" -> {
                                //放音频
                                if (mp3Url.isNotEmpty()) {
                                    initPlayer(mp3Url)
                                }
                            }
                            "普通公告" -> {
                                musicPlayer?.stop()
                                musicPlayer?.onDestroyed()
                            }
                        }
                    }
                }
            }
        }
    }

    private fun initLztek() {
        //红外感应打开识别页面
        Lztek.create(this)?.apply {
            val myObservable = GpioObservable(this)
            val myObserver = MyObserver()
            myObserver.setListener(this@MainActivity)
            myObservable.addObserver(myObserver)
            interval(200, 200, TimeUnit.MILLISECONDS, object : LongObserver() {
                override fun onNext(t: Long) {
                    myObservable.setValue()
                }

                override fun onSubscribe(d: Disposable) {
                    disposable1 = d
                }
            })
        }
    }

    var current = 0
    override fun readValue(value: Int) {
        current += value
        if (current == 0) {
            return
        }
        if (value == 0) {
            controller.record()
        }
    }

    private fun initClient() {
        mNettyTcpClient = NettyTcpClient.Builder()
            .setHost(ip)                    //设置服务端地址
            .setTcpPort(port)               //设置服务端端口号
            .setMaxReconnectTimes(100)        //设置最大重连次数
            .setReconnectIntervalTime(5000)    //设置重连间隔时间。单位：秒
            .setSendheartBeat(false)        //设置发送心跳
            .setHeartBeatInterval(5)        //设置心跳间隔时间。单位：秒
            .setHeartBeatData("I'm is HeartBeatData") //设置心跳数据，可以是String类型，也可以是byte[]，以后设置的为准
            .setIndex(0)                    //设置客户端标识.(因为可能存在多个tcp连接)
            .build()

        mNettyTcpClient.setListener(this) //设置TCP监听
    }

    private fun connect() {
        if (!NetUtils.isNetworkAvailable(this)) {
            toast("设备没有网络")
            return
        }
        if (!mNettyTcpClient.connectStatus) {
            mNettyTcpClient.connect()//连接服务器
        }
    }

    override fun onMessageResponseClient(msg: String, index: Int) {
        LogUtil.e("接收信息$index$msg")
        runOnUiThread {
            try {
                val jsonObject = JSONObject(msg)
                tv_notice.setContent(jsonObject.optString("content"))
                when (jsonObject.optString("type")) {
                    "紧急公告" -> {
                        musicPlayer?.stop()
                        musicPlayer?.onDestroyed()
                        //放音频
                        initPlayer(jsonObject.optString("mp3Url"))
                    }
                    "普通公告" -> {
                        musicPlayer?.stop()
                        musicPlayer?.onDestroyed()
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    override fun onClientStatusConnectChanged(statusCode: Int, index: Int) {
        when (statusCode) {
            STATUS_CONNECT_SUCCESS -> {
                LogUtil.e("CONNECT_SUCCESS")
            }
            STATUS_CONNECT_CLOSED -> {
                LogUtil.e("CONNECT_CLOSED")
            }
            STATUS_CONNECT_ERROR -> {
                LogUtil.e("CONNECT_ERROR")
            }
        }
    }

}